package br.fatec.ppi.projeto.repositorios;

import br.fatec.ppi.projeto.Telefone;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import javax.persistence.Query;

public class TelefoneRepositorio {

    private EntityManager manager;
    private EntityTransaction transaction;

    public TelefoneRepositorio() {
        manager = Persistence.createEntityManagerFactory("modelo").createEntityManager();
        transaction = manager.getTransaction();
    }

    public boolean salvar(Telefone telefone) {
        try {
            transaction.begin();
            manager.persist(telefone);
            transaction.commit();
            return true;
        } catch (Exception e) {
            transaction.rollback();
            return false;
        }
    }

    public boolean atualizar(Telefone telefone) {
        try {
            transaction.begin();
            manager.merge(telefone);
            transaction.commit();
            return true;
        } catch (Exception e) {
            transaction.rollback();
            return false;
        }
    }

    public boolean deletar(Telefone telefone) {
        try {
            transaction.begin();
            manager.remove(telefone);
            transaction.commit();
            return true;
        } catch (Exception e) {
            transaction.rollback();
            return false;
        }
    }

    public Telefone getById(int id) {
        Query query = manager.createQuery("SELECT e FROM Telefone e WHERE e.idTelefone = :id");
        query.setParameter("id", id);
        return (Telefone) query.getSingleResult();
    }
}
